package com.meida.student.app.scholartyrant.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.constants.CommonConstants;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusSubject;
import com.meida.module.bus.client.entity.BusTutorType;
import com.meida.module.bus.client.enums.OrderStatePEnum;
import com.meida.module.bus.client.enums.OrderStateYEnum;
import com.meida.module.bus.client.enums.OrderStateZEnum;
import com.meida.module.bus.client.enums.OrderTypeEnum;
import com.meida.module.bus.provider.service.BusOrderAnswerService;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.bus.provider.service.BusSubjectService;
import com.meida.module.bus.provider.service.BusTutorTypeService;
import com.meida.module.bus.provider.utils.MyDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 学霸接单列表
 *
 * @author zyf
 */
@Component
public class WaitOrderPageListHandler implements PageInterceptor<BusOrder> {

    @Autowired
    private BusOrderService busOrderService;

    @Autowired
    private BusSubjectService busSubjectService;

    @Autowired
    private BusTutorTypeService busTutorTypeService;

    @Autowired
    private BusOrderAnswerService orderAnswerService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public void prepare(CriteriaQuery<BusOrder> cq, PageParams pageParams, EntityMap params) {
        Long userId = OpenHelper.getUserId();
        Integer orderType = params.getInt("orderType");
        String subjectIds = params.get("subjectIds");
        cq.clear();
        cq.select(BusOrder.class, "orderId", "orderNo", "orderType", "answerUserId", "subjectId", "subjectIds", "orderState", "commission", "privateOrder", "rewardAmount", "expectedAmount", "orderDescribe", "coverImg", "appointmentDate", "appointmentTime", "durationTime", "tutorTypeId", "createTime");
        cq.select(BusSubject.class, "subjectTitle");
        cq.eq(BusOrder.class, "orderState");
        //一级分类
        cq.eq(BusOrder.class, "subjectId");
        //待接单,待出价
        cq.in(true, "orderState", OrderStatePEnum.OrderState1.getValue(), OrderStateYEnum.OrderState1.getValue(), OrderStateZEnum.OrderState1.getValue());
        if (orderType == 1) {
            //问答接单(拍照提问和作业无忧)
            cq.ne("orderType", OrderTypeEnum.BookingTutoring.getValue());
        }
        if (orderType == 2) {
            //预约辅导
            cq.eq("orderType", OrderTypeEnum.BookingTutoring.getValue());
        }
        //排除自己发的单
        cq.ne(true, "busOrder.userId", userId);
        //排除已经报价或者接单的
        cq.notInSql("busOrder.orderId", "SELECT oa.orderId from  bus_order_answer oa WHERE oa.answerUserId =" + userId);
        //过滤掉指定用户的订单,只有本人能查看
        cq.and(q -> q.isNull("busOrder.answerUserId").or().eq(true, "answerUserId", userId));
        //匹配二级分类
        cq.regexp("subjectIds", subjectIds);
        cq.createJoin(BusSubject.class).setMainField("subjectId").setJoinField("subjectId");
    }

    @Override
    public void complete(CriteriaQuery<BusOrder> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap entityMap : result) {
            String subjectIds = entityMap.get("subjectIds");
            Long orderId = entityMap.getLong("orderId");
            List<String> subjectTitles = busSubjectService.selectSubjectTitles(subjectIds);
            entityMap.put("subjectTitles", subjectTitles);
            Integer orderType = entityMap.getInt("orderType");
            String orderState = entityMap.get("orderState");
            Long answerUserId = entityMap.getLong("answerUserId");
            Map orderStateDesc = busOrderService.getOrderStateDesc(orderType, orderState);
            entityMap.putAll(orderStateDesc);
            Long tutorTypeId = entityMap.getLong("tutorTypeId");
            //辅导类型
            BusTutorType tutorType = busTutorTypeService.getById(tutorTypeId);
            if (FlymeUtils.isNotEmpty(tutorType)) {
                String tutorTypeName = tutorType.getTutorTypeName();
                Integer chargeType = tutorType.getChargeType();
                BigDecimal tutorPrice = tutorType.getTutorPrice();
                BigDecimal durationTime = entityMap.getBigDecimal("durationTime");
                if (chargeType.equals(1)) {
                    durationTime = durationTime.setScale(0, RoundingMode.HALF_UP);
                }
                String priceUnit = tutorType.getPriceUnit();
                String tutorTitle = MessageFormat.format("{0}(${1}/{2})", tutorTypeName, tutorPrice, priceUnit);
                entityMap.put("tutorTitle", tutorTitle);
                entityMap.put("durationTime", durationTime + priceUnit);
            }
            //是否私单
            Integer privateOrder = entityMap.getInt("privateOrder");
            if (privateOrder.equals(CommonConstants.ENABLED)) {
                if (orderState.equals("P1") || orderState.equals("Y1") || orderState.equals("Z1")) {
                    EntityMap orderAnswer = orderAnswerService.getOrderAnswerByOrderIdAndUserId(orderId, answerUserId);
                    Integer receiveState = orderAnswer.getInt("receiveState");
                    if (receiveState.equals(1)) {
                        entityMap.put("orderStateText", "待支付");
                    }
                }
            }
            String targetTimezone = httpServletRequest.getHeader("targetTimezone");
            String appointmentDate = entityMap.get("appointmentDate");
            String appointmentTime = entityMap.get("appointmentTime");
            if (FlymeUtils.isNotEmpty(appointmentDate)) {
                String appointmentDateTimeStr = appointmentDate + " " + appointmentTime + ":00";
                Date date = DateUtils.strToDate(appointmentDateTimeStr, "yyyy-MM-dd HH:mm:ss");
                Date newDate = MyDateUtils.convertTimezone(date, targetTimezone);
                String newAppointmentDate = DateUtils.formatDate(newDate, "yyyy-MM-dd");
                String newAppointmentTime = DateUtils.formatDate(newDate, "HH:mm");
                String dayOfWeek = DateUtils.getDayOfWeek(DateUtils.formatDate(newAppointmentDate));
                entityMap.put("dayOfWeek", dayOfWeek);
                entityMap.put("appointmentDate", newAppointmentDate);
                entityMap.put("appointmentTime", newAppointmentTime);
            }
            Date createTime = entityMap.get("createTime");

            //格式化显示日期
            String showTime =DateUtils.formatFromTodayByTargetTimezone(createTime,targetTimezone);
            entityMap.put("showTime", showTime);
        }
    }

}
